package com.jeesite.modules.gallery.web;

import com.jeesite.common.web.http.ServletUtils;
import com.jeesite.modules.file.entity.FileUpload;
import com.jeesite.modules.file.service.FileUploadService;
import com.jeesite.modules.file.utils.FileUploadUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.gallery.entity.Gallery;
import com.jeesite.modules.gallery.service.GalleryService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * galleryController
 * @author LaVenderGong
 * @version 2025-08-23
 */
@Controller
@RequestMapping(value = "${adminPath}/gallery/gallery")
public class GalleryController extends BaseController {

	@Autowired
	private GalleryService galleryService;

	@Autowired
	private FileUploadService fileUploadService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Gallery get(Long tid, boolean isNewRecord) {
		return galleryService.get(tid, isNewRecord);
	}

	/**
	 * 查询列表
	 */
//	@RequiresPermissions("gallery:gallery:view")
	@RequestMapping(value = {"list", ""})
	public String list(Gallery gallery, Model model) {
		model.addAttribute("gallery", gallery);
		return "modules/gallery/galleryList";
	}

	/**
	 * 查询列表数据
	 */
//	@RequiresPermissions("gallery:gallery:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Gallery> listData(Gallery gallery, HttpServletRequest request, HttpServletResponse response) {
		gallery.setPage(new Page<>(request, response));
		Page<Gallery> page = galleryService.findPage(gallery);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
//	@RequiresPermissions("gallery:gallery:view")
	@RequestMapping(value = "form")
	public String form(Gallery gallery, Model model) {
		model.addAttribute("gallery", gallery);
		return "modules/gallery/galleryForm";
	}

	/**
	 * 保存数据
	 */
//	@RequiresPermissions("gallery:gallery:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Gallery gallery,HttpServletRequest request) {
		try {
			// 处理文件上传
			MultipartFile imageFile = gallery.getImageFile();
			if (imageFile != null && !imageFile.isEmpty()) {
				// 获取上传目录配置
				String uploadDir = Global.getConfig("file.upload.path").substring(2);

				// 获取允许的图片后缀
				String imageAllowSuffixes = Global.getConfig("file.imageAllowSuffixes");
				List<String> allowedSuffixes = Arrays.asList(imageAllowSuffixes.split(","));

				// 获取文件后缀
				String originalFilename = imageFile.getOriginalFilename();
				String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

				// 检查文件后缀是否允许
				if (!allowedSuffixes.contains(fileSuffix)) {
					return renderResult(Global.FALSE, text("不允许上传该类型的文件，请上传图片文件！"));
				}

				// 检查文件大小
				long maxFileSize = 10 * 1024 * 1024; // 10MB
				if (imageFile.getSize() > maxFileSize) {
					return renderResult(Global.FALSE, text("文件大小不能超过10MB！"));
				}

				// 生成唯一文件名
				String filename = UUID.randomUUID().toString() + fileSuffix;

				// 创建上传目录
				File dir = new File(uploadDir + "/gallery");
				System.out.println("Here!!!!!!!!!!");
				{

					boolean created = dir.mkdirs();
					if (!created) {
						System.out.println("文件夹已存在！");

					}

				}

				// 保存文件
				File file = new File(dir, filename);
				imageFile.transferTo(file);

				// 设置文件路径（相对路径）
				gallery.setUrl("/userfiles/upload/gallery/" + filename);
			}
			System.out.println(gallery);
			// 保存Gallery实体
			galleryService.save(gallery);
			return renderResult(Global.TRUE, text("保存成功！"));
		} catch (Exception e) {
			logger.error("保存失败", e);
			return renderResult(Global.FALSE, text("保存失败：" + e.getMessage()));
		}
	}

	/**
	 * 删除数据
	 */
//	@RequiresPermissions("gallery:gallery:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Gallery gallery) {
		galleryService.delete(gallery);
		return renderResult(Global.TRUE, text("删除gallery成功！"));
	}

}
